// 定义时间段校验
Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field){
        var date = field.parseDate(val);
        if (!date) {
            return false;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        }
        else 
            if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
                var end = Ext.getCmp(field.endDateField);
                end.setMinValue(date);
                end.validate();
                this.dateRangeMin = date;
            }
        return true;
    }
});

// 定义空白图片路径
Ext.BLANK_IMAGE_URL = 'extjs3/resources/images/default/s.gif';

// 定义Flash图表路径
Ext.chart.Chart.CHART_URL = 'extjs3/resources/charts.swf';
Ext.FlashComponent.EXPRESS_INSTALL_URL = 'extjs3/resources/expressinstall.swf';

// 定义FormPanel默认样式
Ext.apply(Ext.FormPanel.prototype, {
    bodyCssClass: 'x-bee-form-background-fix'
});

// 定义提示框宽度
Ext.MessageBox.minWidth = 400;

// 定义程序的命名空间
var Bee = {};
Bee.tree = {};
Bee.data = {};
Bee.form = {};
Bee.grid = {};
Bee.ext = {};

// 是否启用注销
Bee.hasLogout = true;

// 加载插件
Bee.plugins = {
    root: ['Window', 'Portal', 'DatePickerPlus'],
    tree: ['DWRTreeLoader', 'CheckTreePanel', 'TreeCheckNodeUI'],
    data: ['DWRProxy', 'DWRPageProxy', 'DWRReader', 'DWRPageReader', 'DWRStore'],
    form: ['DWRForm', 'DWRComboBox', 'ArrayComboBox', 'FileUploadField', 'TreeCombo', 'LovCombo', 'TreeComboBox', 'ComboBoxCheckTree'],
    grid: ['CheckColumn', 'ColumnHeaderGroup', 'RadioSelectionModel', 'ListGrid', 'PageGrid', 'RowEditor', 'RowExpander']
};

for (var type in Bee.plugins) {
    var path = type == 'root' ? '' : type + '/';
    
    if (Bee.plugins[type] instanceof Array) {
        for (var index = 0; index < Bee.plugins[type].length; index++) {
            var name = Bee.plugins[type][index];
            document.write('<script type="text/javascript" src="extjs3/plugins/' + path + name + '.js"></script>');
        }
    }
}

// CM模块对象
Bee.module = function(main){
    this.main = main;
    this.init(main);
    this.main.on('beforedestroy', function(o){
        if (o.associatedComp && o.associatedComp instanceof Array) {
            for (var i = 0; i < o.associatedComp.length; i++) {
                Ext.destroy(o.associatedComp[i]);
            }
        }
    });
};

Ext.extend(Bee.module, Ext.util.Observable, {
    init: Ext.emptyFn
});

// CM主框架对象
Bee.app = function(north, west, center){
    this.init(north, west, center);
};

Ext.extend(Bee.app, Ext.util.Observable, {
    init: function(north, west, center){
        this.north = north;
        this.west = west;
        this.center = center;
        this.body = center;
        var viewport = new Ext.Viewport({
            layout: 'border',
            layoutConfig: {
                animate: false
            },
            items: [north, west, center]
        });
        this.loadMask = new Ext.LoadMask(this.body.body, {
            msg: "加载中，请稍候..."
        });
    }
});

Bee.openTab = function(node){
    if (Ext.getCmp('welcome-tab-pertaskmanwin')) {
        Ext.getCmp('welcome-tab-pertaskmanwin').hide();
    }
    if (node.attributes.leaf == 1) {
        var moduleId = 'tab_menu_' + node.attributes.link.replace(/\//img, '_').replace('.js', '');
        if (cmApp.body.findById(moduleId)) {
            cmApp.body.findById(moduleId).show();
            return;
        }
        cmApp.loadMask.show();
        var panel = cmApp.body.add({
            id: moduleId,
            title: node.attributes.cname,
            sid: node.attributes.sid,
            closable: true,
            layout: 'fit'
        }).show();
        Ext.Ajax.request({
            method: 'GET',
            url: 'modules/' + node.attributes.link,
            success: function(response){
                var module = eval(response.responseText);
                cmApp[moduleId] = new module(panel);
                cmApp.loadMask.hide();
            }
        });
    }
};

// 公用提示消息方法
Bee.msg = function(msg, title){
    function createBox(t, s){
        return ['<div class="msg">', '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3 style="float:left;">', t, '</h3><a class="qtip-close" onclick="Bee.closeMSG(1, event);"></a>', '<div style="clear:both;">', s, '</div>', '</div></div></div>', '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', '</div>'].join('');
    }
    this.msgCt = Ext.DomHelper.insertFirst(document.body, {
        id: 'msg-div'
    }, true);
    title = title || '提示';
    this.msgCt.alignTo(document.body, 't-t');
    var m = Ext.DomHelper.append(this.msgCt, {
        html: createBox(title, msg)
    }, true);
    m.slideIn('t').pause(2).ghost('t', {
        remove: true
    });
};

// 关闭消息提示方法
Bee.closeMSG = function(o, e){
    var evt = e || event;
    var obj = evt.srcElement || evt.target;
    var msgDiv = Ext.get(obj).up('.msg');
    if (msgDiv) {
        msgDiv.setStyle({
            display: 'none'
        });
    }
};

Array.prototype.findBy = function(f, v){
    if (this.length === 0) {
        return [];
    }
    var r = [];
    for (var i = 0; i < this.length; i++) {
        if (typeof this[i] == 'object') {
            if (this[i][f] == v) {
                r.push(this[i]);
            }
        }
        else {
            if (this[i] == f) {
                r.push(this[i]);
            }
        }
    }
    return r;
};

// 调试DWR用方法
DWREngine.setErrorHandler(function(msg, ex){
    if (msg.indexOf('未取得当前用户信息') > -1) {
        Ext.Msg.show({
            title: '登录超时',
            msg: msg,
            buttons: Ext.Msg.OK,
            fn: function(){
                location.replace('index.html');
            }
        });
    }
    else {
        Ext.Msg.alert('远程调用失败', msg);
    }
});

if ('function' !== typeof RegExp.escape) {
    RegExp.escape = function(s){
        if ('string' !== typeof s) {
            return s;
        }
        return s.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1');
    };
}

Bee.sizeWin = function(title, html){
    var sizeWin;
    var rgExp = /\n/ig;
    html = html.replace(rgExp, '<br/>');
    if (!sizeWin) {
        var tip = new Ext.slider.Tip({
            getText: function(thumb){
                return String.format('<b>{0}%</b>', thumb.value + '0');
            }
        });
        var slider = new Ext.Slider({
            width: 400,
            value: 20,
            minValue: 10,
            maxValue: 50,
            plugins: tip,
            listeners: {
                changecomplete: function(o, newValue){
                    o.ownerCt.ownerCt.body.setStyle('font-size', newValue + 'px');
                }
            }
        });
        sizeWin = new Ext.Window({
            title: title,
            width: 600,
            height: 400,
            autoScroll: true,
            closeAction: 'hide',
            modal: true,
            html: html,
            bodyStyle: 'padding:10px; font-size:20px;',
            fbar: [slider, {
                text: '关闭',
                handler: function(o){
                    o.ownerCt.ownerCt.hide();
                }
            }]
        });
    }
    else {
        sizeWin.setTitle(title);
        sizeWin.body.update(html);
    }
    return sizeWin.show();
};
